package com.cyy.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.path.json.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class YmlParser {

    /**
     * 读取指定yaml文件的内容并保存在map对象中
     *
     * @param path yaml 文件路径
     * @return
     */
    public static Map<String, Object> read_yaml(String path) {
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Yaml yaml = new Yaml();
        return yaml.loadAs(inputStream, Map.class);

    }

    /**
     * 从Map中获取配置的值
     * 传的key支持两种形式, 一种是单独的,如user.path.key
     * 一种是获取数组中的某一个,如 user.path.key[0]
     *
     * @param key
     * @param properties map对象
     * @return
     */
    public static Object getValueByKey(Map properties,String key) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String jsonString = objectMapper.writeValueAsString(properties);
            JsonPath from = JsonPath.from(jsonString);
            return from.get(key);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
        read_yaml("src/main/resources/android.ui.element.path.yaml");
        // "登录页":{"输入框手机号码":"id=com.cyyserver:id/et_phonenum","输入框验证码":"id=com.cyyserver:id/et_checkcode",
//        System.out.println(getValueByKey("登录页.输入框手机号码"));
        ;
    }


}
